import axios from 'axios'; // 引入axios
import router from '../router'
import storage from '../util/storage' // 缓存工具
import ele from 'element-ui';

let instance = axios.create({
    timeout: 1000 * 30
});

axios.defaults.withCredentials = true;
axios.defaults.headers['Content-Type'] = 'application/json';

instance.interceptors.response.use(
    response => {
        if (response.data.code == 99999) {
            storage.localRemove("userinfo");
            router.replace({
                path: '/login'
            });
        }
        return response;
    },
    error => {
        if (error.response) {
            storage.localRemove("userinfo");
            router.replace({
                path: '/login'
            });
        }
        console.log(error);
        return Promise.reject(error);
    }
);

router.beforeEach((to, from, next) => {
    let token = storage.localGet('userinfo');
    if (to.meta.requireAuth) {
        if (token) {
            next();
        } else {
            next({
                path: '/login'
            })
        }
    } else {
        next();
    }
})
// 路由鉴权
router.beforeEach((to, from, next) => {
    let init  = storage.sessionGet('init');
    let title = ' - 后台管理';
    if(init){
        title = ' - ' + init.site_title
    }
    if (to.meta.title) {
        document.title = to.meta.title + title
    }
    next();
})
// 设置页面标题

export default instance;